<?php
/**
 *  A simple class for querying MySQL
 */
class DataAccess {
    /**
    * Private
    * $db stores a database resource
    */
    private $db;
    
    /**
    * Private
    * $query stores a query resource
    */
    private $query; // Query resource
    
    static function getInstance($dbname) {
        global $database_runner;
        
		if((!isset($database_runner)) || (!$database_runner) || (!array_key_exists($dbname, $database_runner))){
			$config = require(APPLICATION_ROOT . '/config/' . 'database_config.php');
            if(!isset($config[$dbname])) {
                return FALSE;
            }
            
            $database_runner[$dbname] =  new DataAccess($config[$dbname]['host'], $config[$dbname]['user'], $config[$dbname]['password'], $config[$dbname]['database']);
		}
        return $database_runner[$dbname];
    }
    
    //! A constructor.
    /**
    * Constucts a new DataAccess object
    * @param $host string hostname for dbserver
    * @param $user string dbserver user
    * @param $pass string dbserver user password
    * @param $db string database name
    */
    function DataAccess ($host,$user,$pass,$db) {
        //echo "mysql_connect($host,$user,$pass)"; 
        $this->db=@mysql_connect($host,$user,$pass) or die('Connect '.$host.' fail！'.mysql_error());
        mysql_select_db($db,$this->db);
        mysql_query("SET NAMES utf8");
    }

    /**
     * Get database server connection
     * @param return resource
     */
    static function getMysqlConn($dbname) {
        static $config;
        if($config==null)
        {
            $config = require(APPLICATION_ROOT . '/config/database_config.php');
        }
        if(!isset($config[$dbname])) {
            return FALSE;
        }

        $conn = @mysql_connect($config[$dbname]['host'], $config[$dbname]['user'], $config[$dbname]['password']);
        mysql_query("SET NAMES utf8");

        return $conn;
    }

   /**
    * close connection
    * @return boolean 
    */
    function close() {
        return mysql_close($this->db);
    }
	
   /**
    * free resultset
    * @return boolean 
    */
    function freeResult() {
        return mysql_free_result ($this->query);
    }

   /**
    * start for transaction
    * @return void 
    */
    function start() {
        mysql_query("SET AUTOCOMMIT=0"); 
        mysql_query("START TRANSACTION");
    }

   /**
    * Commit for transaction
    * @return void
    */
    function commit() {
        mysql_query("COMMIT");
    }
	
   /**
    * rollback for transaction
    * @return void
    */
    function rollback() {
        mysql_query("ROLLBACK");
    }

    /**
    * query the records in database
    * @param $sql string the database update to run
    * @return boolean
    */
    function query($sql) {
        $this->query =  mysql_query($sql, $this->db);
        
        return $this->query;
    }

   /**
    * Insert the records into database
    * @param $sql string the database insert to run
    * @return boolean
    */
    function insert($sql) {
        return mysql_query($sql, $this->db);
    }

   /**
    * update the records in database
    * @param $sql string the database update to run
    * @return boolean
    */
    function update($sql) {
        return mysql_query($sql, $this->db);
    }
	
   /**
    * get the new insert record id
    * @return int
    */
    function getInsertedId() {
    	return mysql_insert_id($this->db);
    }
	
    //! An accessor
    /**
    * Fetches a query resources and stores it in a local member
    * @param $sql string the database query to run
    * @return void
    */
    function fetch($sql) {
        $this->query = mysql_query($sql, $this->db); // Perform query here
    }
	
    //! An accessor
    /**
    * Returns an associative array of a query row
    * @return mixed
    */
    function getRow () {
    	return mysql_fetch_assoc($this->query);
    }
    function get_row () {
        return mysql_fetch_row($this->query);
    }
    function get_num_rows()
    {
        return mysql_num_rows($this->query);
    }
    
    /*
     * 2011-4-22 16:25:53 add by Helen
     */
    function getRows($sql){
    	$this->query($sql);
    	$ret = array();
    	while($row = mysql_fetch_assoc($this->query)){
    		$ret[] = $row;
    	}
    	$this->freeResult();
    	return $ret;
    }
    function getValue($sql){
    	$this->query($sql);
    	$ret = 0;
    	$row = mysql_fetch_row($this->query);
    	if(isset($row[0])){
    		$ret = $row[0];
    	}
    	$this->freeResult();
    	return $ret;
    }
	
		 /**
     * 将数组转换成字符串
     * @return mix 成功则返回string，否则false
     * @param array $param 需要转换的数组
     * @param string $type 指定类别，更新记录为update，插入数据为insert
     */
    function array_to_string($param, $type = 'insert')
    {
        if (empty($param) || !is_array($param))
        {
            return false;
        }
        if (is_array($param) && $type == 'insert')
        {
            $fields = '';
            $values = '';
            foreach ($param as $key=>$value)
            {               
                 $fields .= "`$key`,";
                $values .= "'".$value."',";
            }
            $string = "(".substr($fields, 0, -1).") values (".substr($values, 0, -1).")";
            return $string;
        }
        elseif (is_array($param) && $type == 'update')
        {
            $string = '';
            foreach ($param as $key=>$value)
            {
                ###如果在前面加=，则表示自增              
            	if (substr($value, 0, 2) == '=-')
                {
                    $string .= "`$key`" ."=`".$key."`-".substr($value, 2).",";
                }
                elseif (substr($value, 0, 1) == '=')
                {
                    $string .= "`$key`" ."=`".$key."`+".substr($value, 1).",";
                }
                else 
                {
                    $string .= "`$key`" ."='".$value."',";
                }
            }
            $string = substr($string, 0, -1);
            return $string;           
        }
        return false;
    }
    
}
?>
